package com.nuc.zyt.day05.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @ClassName App
 * @Description TODO
 * @Author 耀酱
 * @Date 2023/5/31 9:52
 * @Version 1.0
 */

public class App {
    public static void main(String[] args) {

        reader(new File("Day01/src/com/nuc/zyt/day05/nio/config.txt"));

        //copyFile();  复制文件，
        // java封装好的 transferfrom()方法复制文件

    }

    public static void write(File file,String str){
        try {
            // file = new File("Day01/src/com/nuc/zyt/day05/nio/config.txt");
            FileOutputStream fileOutputStream = new FileOutputStream(file);

            FileChannel channel = fileOutputStream.getChannel();
            // 分配缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            byteBuffer.put(str.getBytes()); // 读入缓冲区域

            byteBuffer.flip(); // 切换到写模式

            channel.write(byteBuffer); // 通道写出

            byteBuffer.flip(); // 切换模式

            channel.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void reader(File file){
        try {
            // file = new File("Day01/src/com/nuc/zyt/day05/nio/config.txt");
            FileInputStream fileInputStream = new FileInputStream(file);

            FileChannel channel = fileInputStream.getChannel();
            // 分配缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            channel.read(byteBuffer);

            byteBuffer.flip();

           String str = new String(byteBuffer.array(),0,byteBuffer.remaining());

            System.out.println(str);

            channel.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void copyFile(File file1,File file2){
        try(
                FileInputStream fileInputStream = new FileInputStream(file1);
                FileOutputStream fileOutputStream = new FileOutputStream(file2);
        ){
            FileChannel channel1 = fileInputStream.getChannel();
            FileChannel channel2 = fileOutputStream.getChannel();

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

           while (true){
               byteBuffer.clear(); // 刷新缓冲区
               // 读入缓冲区
               int read = channel1.read(byteBuffer);
               if(read == -1){
                   // 没有数据了
                   break;
               }
               byteBuffer.flip(); // 变为读状态
               channel2.write(byteBuffer);
           }
           channel1.close();
           channel2.close();


        }catch (Exception e){

        }

    }
}
